<?php

/**
 * 产生随机字符串
 *
 * @param    int        $length  输出长度
 * @param    string     $chars   可选的 ，默认为 0123456789
 * @return   string     字符串
 */
function random($length, $chars = '0123456789') {
    if($chars=='chars') {
        $chars='abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    }
    $hash = '';
    $max = strlen($chars) - 1; 
    for($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }    
    return $hash;
}

/**
 * 获取请求ip
 *
 * @return ip地址
 */
function ip() {
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }    
    return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}

//把IP地址转换为数值型用于判断是否在某个IP段类
function myip2long($ip){  
    $ip_arr = explode('.',$ip);  
    $iplong = (16777216 * intval($ip_arr[0])) + (65536 * intval($ip_arr[1])) + (256 * intval($ip_arr[2])) + intval($ip_arr[3]);  
    return $iplong;  
}

//手机号验证
function check_mobile($mobile) {
    $pattern = '/^[1][3-9]+\d{9}/i';
    $preg_ret = preg_match_all($pattern, $mobile, $m);
    if(false === $preg_ret || 0 == $preg_ret) {
        return false;
    }
    return true;
}

function format_number($number) {

    $num_str = '';
    $unit = 10000;
    if(intval($number) < $unit) {
        return $number;
    }
    if(intval($number) >= $unit) {
        $w = floor(intval($number) / $unit);
        $num_str = $w . 'w';
    }
    if((intval($number) % $unit) > 0) {
        $num_str .= '+';
    }
    return $num_str;
}

function format_price($price) {

    $price = $price/100;

    return $price;

}

//正则 汉字 字母 数字 下划线
function check_user_name($str, $min=2, $max=16){
    $pattern = "/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_]{".$min.",".$max."}$/u";
    $preg_ret = preg_match_all($pattern, $str, $m);
    if(false === $preg_ret || 0 == $preg_ret) {
        return false;
    }else{
        return true;
    }
}

function android_check($os='', $sv='', $channel=0) {
    if (!$os || !$sv || !$channel) {
        return 0; 
    }
    if (strtolower($os) != 'android') {
        return 0;
    }
    if (!isset(ANDROID_CHECK_INFO[DUPW_ID]) 
        || !isset(ANDROID_CHECK_INFO[DUPW_ID]['sv'])
        || $sv != ANDROID_CHECK_INFO[DUPW_ID]['sv']) {
        return 0; 
    }
    $channel = intval($channel);
    if (!isset(ANDROID_CHECK_INFO[DUPW_ID]['channel_set'][$channel])) {
        return 0; 
    }
    return 1;
}

function get_site_color() {
    if (DUPW_ID == JINRI) {
        return '#1882FF'; 
    }
    return '#EF3A3A';
}

function strfread_num($read_num, $decimal_num=0) {
    if ($read_num >= 100000000) {
        $str = number_format($read_num/100000000, $decimal_num, '.', '').'亿';
    } elseif ($read_num >= 10000) {
        $str = number_format($read_num/10000, $decimal_num, '.', '').'万';
    } elseif ($read_num >= 1000) {
        $str = number_format($read_num/1000, $decimal_num, '.', '').'千';
    } else {
        $str = $read_num;
    }
    return $str;
}


function base64url_encode($data) { 
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
} 


function base64url_decode($data) { 
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT)); 
}

function mbStrreplace($content,$to_encoding="UTF-8",$from_encoding="UTF-8") {
    $str=mb_convert_encoding("　",$to_encoding,$from_encoding);
    $content=mb_eregi_replace($str," ",$content);
    $content=trim($content);
    return $content;
}

function getMsec(){//返回毫秒时间戳
    $arr = explode(' ',microtime());
    $hm = 0;
    foreach($arr as $v){
        $hm += floor($v * 1000);
    }
    return $hm;
}

function message_logger($level, $info)
{
    if ( ! in_array($level, ['info', 'debug', 'error']))
    {
        $level = 'debug';
        $info .= ' log level error, set level is ' . $level;
    }
    $debug_info = debug_backtrace();
    $method = $debug_info[1]['class'] . '::' . $debug_info[1]['function'];
    $line = $debug_info[0]['line'];
    log_message($level, sprintf('[%s][%s] %s', $method, $line, $info));
}

function better_array_uniq(array $array)
{
    return array_values(array_unique($array));
}

function curlRequest($url, $request_method, $request_data = [], $header = [])
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request_method);
    if ( ! empty($header))
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    if ( ! empty($request_data))
    {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request_data, null, '&'));
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    $info = curl_exec($ch);
    $errno = curl_errno($ch);
    $curl_info = curl_getinfo($ch);

    log_message('info', '==== curl request_data_json is ' . var_export($request_data, true));
    log_message('info', '==== curl full_url is ' . $url);

    curl_close($ch);

    if($errno !== 0)
    {
        log_message('error', ' Call service failed. (' . $errno . '), full_url: (' . $url . ')');
        return [
            'result_code' => -1,
            'result_msg' => "服务调用失败(" . $errno . ")"
        ];
    }

    $result = json_decode($info, true);
    if($result === false)
    {
        log_message('error', ' Call service failed, return value is not json');
         return [
            'result_code' => -1,
            'result_msg' => "服务调用失败(-2)"
        ];
    }
    return $result;
}

function toCamelCase($str)
{
    $array = explode('_', $str);
    $result = $array[0];
    $len=count($array);
    if($len>1)
    {
        for($i=1;$i<$len;$i++)
        {
            $result.= ucfirst($array[$i]);
        }
    }
    return $result;
}

function toUnderScore($str)
{
    $dstr = preg_replace_callback('/([A-Z]+)/',function($matchs)
    {
        return '_'.strtolower($matchs[0]);
    },$str);
    return trim(preg_replace('/_{2,}/','_',$dstr),'_');
}

function toCamelCaseKey($arr)
{
    $tmp = [];
    if (is_array($arr)) {
        foreach ($arr as $k => $v)
        {
            if (is_array($v))
            {
                $v = toCamelCaseKey($v);
            }
            if (strpos($k, '_')) {
                $key = ucwords(str_replace('_', ' ', $k));
                $key = str_replace(' ', '', lcfirst($key));
                $tmp[$key] = $v;
            } else {
                $tmp[$k] = $v;
            }
        }
    }
    return $tmp;
}